<template>
  <el-dialog :title="`${form.sectionId ? '修改' : '添加'}标段`" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="820px" @closed="$refs.form.resetFields()">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="sectionId" class="hide" />
      <el-form-item prop="constructionName" class="hide" />
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="成本分期项目" prop="curProjectId">
            <el-select v-model="form.curProjectId" placeholder="请选择成本分期项目" filterable :disabled="isEdit" :loading="prjLoading" style="width: 100%" @change="onChangeProject">
              <el-option v-for="project in projectList" :key="project.fid" :label="project.cflastname" :value="project.fid" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标段类型" prop="sectionType">
            <el-select v-model="form.sectionType" placeholder="请选择标段类型" :disabled="isEdit || disableAction" style="width: 100%" @change="onChangeSectionType">
              <el-option v-for="dict in dict.type.gcx_section_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标段名称" prop="sectionName">
            <el-select v-model="form.sectionName" placeholder="请选择标段名称" style="width: 100%" @change="onChangeSectionName">
              <el-option v-for="item in sectionNameList" :key="item.label" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标段别名" prop="sectionAlias"><el-input v-model.trim="form.sectionAlias" placeholder="请输入标段别名" :maxlength="50" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同" prop="contractId">
            <el-select v-model="form.contractId" placeholder="请选择合同" filterable :loading="contractLoading" style="width: 100%" @change="onChangeContract">
              <el-option v-for="item in contractList" :key="item.contractId" :label="item.contractName" :value="item.contractId" style="height: auto">
                <div style="padding: 5px 0">
                  <div style="font-size: 14px; line-height: 24px">{{ item.contractName }}</div>
                  <div style="color: #8492a6; font-size: 12px; line-height: 14px">{{ item.showConstructionNames }}</div>
                </div>
              </el-option>
              <el-option label=" " :value="EMPTY_CONTRACT" style="color: #e6a23c; text-align: center">
                <i class="el-icon-warning" />
                找不到合同，选择承建商
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="承建商" prop="constructionId">
            <el-select v-model="form.constructionId" placeholder="请选择承建商" filterable :loading="constructionLoading" style="width: 100%" @change="onChangeConstructionId">
              <el-option v-for="item in showConstructionList" :key="item.constructionId" :label="item.constructionName" :value="item.constructionId" />
              <el-option value="" @click.native="showEditRdcConstruction = true" v-if="canAddConstruction">
                <el-button size="mini" type="text" icon="el-icon-plus">添加承建商</el-button>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联土建标段" prop="relationSectionId" key="relationSectionId" v-if="isHardcover">
            <el-select v-model="form.relationSectionId" placeholder="请选择关联标段" filterable clearable :loading="sectionListLoading" style="width: 100%">
              <el-option v-for="item in civilSectionList" :key="item.sectionId" :label="`${item.sectionName} ${item.constructionName || ''}`" :value="item.sectionId" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark"><el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :maxlength="255" /></el-form-item>
      <el-form-item label="选择楼栋" prop="sectionBuilds" v-loading="buildingLoading">
        <el-transfer v-model="sectionBuildsSelect" :data="buildingList" :props="{ key: 'fid', label: 'fnameL2' }" :titles="['待选项', '已选项']" />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="disableAction" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>

    <EditRdcConstruction ref="EditRdcConstruction" v-model="showEditRdcConstruction" @ok="getConstructionList" />
  </el-dialog>
</template>
<script>
// 添加或修改标段
import auth from '@/plugins/auth'
import { nameRule } from '@/utils/validate'
import { editFormMixin } from '@/utils/mixin'
import { SECTION_TYPE } from '@/utils/baseData'
import { selectProjectExcludeCfProjectStage } from '@/api/baseManage/project'
import { listBuildingManage } from '@/api/baseManage/buildingManage'
import { listGcxSection, addGcxSection, updateGcxSection, listGcxContract } from '@/api/baseManage/gcxSection'
import { listRdcConstruction } from '@/api/qualityManage/cq'
import EditRdcConstruction from '@/views/cq/components/EditRdcConstruction'
import { sectionNameList, EMPTY_CONTRACT } from '../common'
const sectionName2value = sectionNameList.reduce((o, i) => !void (o[i.label] = i.value) && o, {})

export default {
  components: { EditRdcConstruction },
  mixins: [editFormMixin],
  dicts: ['gcx_section_type'],
  data() {
    return {
      sectionNameList,
      EMPTY_CONTRACT,
      primaryKey: 'sectionId',
      addApi: addGcxSection,
      updateApi: updateGcxSection,
      form: {
        sectionId: '',
        sectionName: '',
        sectionAlias: '',
        sectionType: '',
        curProjectId: '',
        sectionBuilds: [],
        contractId: '',
        constructionId: '',
        constructionName: '',
        relationSectionId: '',
        remark: '',
        seq: 0
      },
      rules: {
        sectionName: [{ required: true, message: '请选择标段名称' }],
        sectionAlias: [nameRule],
        sectionType: [{ required: true, message: '请选择标段类型' }],
        curProjectId: [{ required: true, message: '请选择成本分期项目' }],
        sectionBuilds: [{ required: true, message: '请选择楼栋' }],
        contractId: [{ required: true, message: '请选择合同' }],
        constructionId: [{ required: true, message: '请选择承建商' }],
        relationSectionId: [{ required: true, message: '请选择关联土建标段' }]
      },
      prjLoading: false,
      projectList: [],
      contractLoading: false,
      contractList: [],
      constructionLoading: false,
      constructionList: [], // 承建商
      contractConstructionList: [], // 合同内的承建商
      showEditRdcConstruction: false, // 添加承建商的弹窗
      buildingLoading: false,
      buildingList: [],
      sectionListLoading: false,
      sectionList: []
    }
  },
  computed: {
    isEdit() {
      return !!this.form.sectionId
    },
    isHardcover() {
      // 标段类型为 精装
      return this.form.sectionType === SECTION_TYPE.HARDCOVER
    },
    isEmptyContract() {
      return this.form.contractId === EMPTY_CONTRACT
    },
    disableAction() {
      return this.prjLoading || this.contractLoading || this.constructionLoading || this.buildingLoading || this.sectionListLoading
    },
    showConstructionList() {
      return !this.form.contractId ? [] : !this.isEmptyContract ? this.contractConstructionList : this.constructionList
    },
    canAddConstruction() {
      return auth.hasPermi('baseManage:rdcConstruction:add') && this.isEmptyContract
    },
    civilSectionList() {
      // 过滤出土建标段
      return this.sectionList.filter(i => i.sectionType === SECTION_TYPE.CIVIL)
    },
    // 楼栋多选
    sectionBuildsSelect: {
      get() {
        const arr = this.form.sectionBuilds || []
        return arr.map(i => i?.buildId).filter(i => i)
      },
      set(val) {
        this.form.sectionBuilds = val.map(buildId => ({ buildId }))
      }
    }
  },
  created() {
    this.getProjectList()
  },
  methods: {
    async opened(item = {}) {
      this.contractConstructionList = []
      if (!this.projectList.length) this.getProjectList()
      this.getConstructionList()
      this.getContractList()
      await this.getSectionList()
      this.getBuildingList()
    },
    // 获取授权的用户的项目列表
    async getProjectList() {
      this.prjLoading = true
      const res = await selectProjectExcludeCfProjectStage({ needUserId: true }).catch(() => false)
      this.prjLoading = false
      if (res === false) return
      this.projectList = res.data || []
    },
    async onChangeProject() {
      this.sectionBuildsSelect = []
      this.form.contractId = ''
      this.form.constructionId = ''
      this.form.constructionName = ''
      this.form.relationSectionId = ''
      this.getContractList()
      await this.getSectionList()
      this.getBuildingList()
    },
    onChangeSectionType() {
      this.sectionBuildsSelect = []
      this.form.contractId = ''
      this.form.constructionId = ''
      this.form.constructionName = ''
      this.getContractList()
      this.getBuildingList()

      // 精装才有关联标段，非精装则清除
      if (!this.isHardcover) this.form.relationSectionId = ''
    },
    onChangeSectionName(name) {
      if (!name) return
      // 根据标段名称更改 seq
      this.form.seq = sectionName2value[name]
    },
    async getBuildingList() {
      this.buildingList = []
      const { isEdit, sectionList } = this
      const { sectionId, curProjectId, sectionType } = this.form
      if (!curProjectId || !sectionType) return

      const opt = { cfcurprojectid: curProjectId }
      this.buildingLoading = true
      const res = await listBuildingManage(opt).catch(() => false)
      this.buildingLoading = false
      if (res === false) return

      const data = res.data || []
      // 禁用其他标段已选的楼栋
      const buildIds = {}
      const sectionList2 = sectionList.filter(i => i.sectionType === sectionType)
      const sectionList3 = isEdit ? sectionList2.filter(i => i.sectionId !== sectionId) : sectionList2
      sectionList3.map(i => i.sectionBuilds?.map(build => (buildIds[build.buildId] = 1)))
      data.map(i => {
        i.disabled = !!buildIds[i.fid]
      })

      this.buildingList = data
    },
    // 合同
    async getContractList() {
      this.contractList = []
      const { curProjectId, sectionType, contractId } = this.form
      if (!curProjectId || !sectionType) return

      const opt = { pageSize: 9999, curProjectId }
      if (sectionType) opt.contractType = sectionType

      this.contractLoading = true
      const res = await listGcxContract(opt).catch(() => false)
      this.contractLoading = false
      if (res === false) return

      const data = res.rows || []
      data.map(i => {
        // 将乙丙方承建商合为数组
        const constrList = []
        if (i.constructionId) constrList.push({ constructionId: i.constructionId, constructionName: i.constructionName })
        if (i.constructionCid && i.constructionCid !== i.constructionId) constrList.push({ constructionId: i.constructionCid, constructionName: i.constructionCname })
        i.constructionList = constrList
        i.showConstructionNames = constrList.map(r => r.constructionName).join(', ')
      })
      this.contractList = data

      // 初始赋值合同内的承建商
      if (contractId) {
        const item = data.find(i => i.contractId === contractId)
        this.contractConstructionList = item?.constructionList || []
      }
    },
    onChangeContract(contractId) {
      if (!contractId || this.isEmptyContract) {
        this.contractConstructionList = []
        this.form.constructionId = ''
        this.form.constructionName = ''
        return
      }

      // 更改承建商
      const item = this.contractList.find(i => i.contractId === contractId)
      const constrList = item?.constructionList || []
      this.contractConstructionList = constrList
      // 取丙方承建商
      const lastItem = constrList[constrList.length - 1] || {}
      this.form.constructionId = lastItem.constructionId || ''
      this.form.constructionName = lastItem.constructionName || ''

      // 更改楼栋。合同内的楼栋，过滤出在列表内、没被禁用、没被选的
      const buildIds = (item.buildingId || '').split(',').filter(i => i)
      const selected = this.sectionBuildsSelect
      const selectable = this.buildingList.filter(i => !i.disabled).map(i => i.fid)
      const unselected = buildIds.filter(i => !selected.includes(i) && selectable.includes(i))
      if (!unselected.length) return
      this.sectionBuildsSelect = this.sectionBuildsSelect.concat(unselected)
    },
    // 承建商
    async getConstructionList() {
      this.constructionLoading = true
      const res = await listRdcConstruction().catch(() => false)
      this.constructionLoading = false
      if (res === false) return
      this.constructionList = res.data || []
    },
    // 承建商改变时，手动赋值 constructionName
    onChangeConstructionId(id) {
      if (!id) return (this.form.constructionName = '')
      const list = this.showConstructionList || []
      const item = list.find(i => i.constructionId === id)
      this.form.constructionName = item?.constructionName || ''
    },
    // 土建标段
    async getSectionList() {
      this.sectionList = []
      const { curProjectId } = this.form
      if (!curProjectId) return

      const opt = { pageSize: 9999, curProjectId }
      this.sectionListLoading = true
      const res = await listGcxSection(opt).catch(() => false)
      this.sectionListLoading = false
      if (res === false) return
      this.sectionList = res.rows || []
    }
  }
}
</script>
<style lang="scss" scoped>
// 覆盖穿梭框样式
/deep/ {
  .el-transfer-panel {
    width: 292px;
  }
  .el-transfer__buttons .el-button {
    display: block;
    margin-left: 0px;
    padding: 10px;
    border-radius: 50%;
  }
}
</style>
